<script setup>
	import {
		onLoad,
		onShow
	} from "@dcloudio/uni-app";
	import {
		ref,
		reactive,
		onBeforeUnmount,
		computed,
	} from 'vue';
	import {
		verifyMobile,
		verifyCode,
		verifyPassword,
	} from "../../utils/verify";
	import requestApi from '../../utils/requestApi'
	import { encrypt,decrypt } from '../../utils/encrypt.js'

	const loginForm1 = reactive({
		mobile: "18134748477",
		code: "",
	})
	const loginForm2 = reactive({
		mobile: "18134748477",
		password: "123456",
	})
	const isAgree = ref(true)

	// 导航栏
	function onBack() {
		uni.navigateBack()
	}

	// 标签栏
	const tabbarIndex = ref(0)
	const tabbarList = ref([{
			name: '验证码登录',
		},
		{
			name: '密码登录',
		},
	])

	function onChangeTabbar(item, index) {
		tabbarIndex.value = index
	}
	// 登录
	const login_loading = ref(false)

	function login() {
		if (!isAgree.value) {
			uni.showToast({
				title: '请同意用户协议',
				icon: 'none'
			})
			return
		}
		switch (tabbarIndex.value) {
			case 0:
				loginByCode()
				break;
			case 1:
				loginByPassword()
				break;
			default:
				break;
		}
	}

	// {
	// 	"access_token": "23f9eb40-bf8f-4e00-b1eb-cbdd48629aa9",
	// 	"token_type": "bearer",
	// 	"refresh_token": "8a524988-f0c2-44db-99f1-e6a6b2bd601c",
	// 	"expires_in": 86399560,
	// 	"scope": "all"
	// }
	function loginSuccess(data) {
		if (data.access_token) {
			uni.setStorageSync('token', data)
			uni.redirectTo({
				url: '/pages/user/cardManage'
			})
		} else {
			uni.showToast({
				title: '缺少必要的数据',
				icon: 'error'
			})
		}
	}
	// 验证码登录
	let timer = 0,
		time = 60;
	const currentTime = ref(0)
	const codeText = computed(() => currentTime.value > 0 ? `${currentTime.value}秒` : '获取验证码')

	function onSendCode() {
		try {
			if (!verifyMobile(loginForm1.mobile.trim())) {
				uni.showToast({
					title: '手机号错误',
					icon: 'none'
				})
				return
			}
			if (currentTime.value > 0) {
				return
			}
			currentTime.value = time
			timer = setInterval(() => {
				currentTime.value--
				if (currentTime === 0) {
					clearSendCodeTimer()
				}
			}, 1000)
		} catch (e) {
			console.error(e)
			uni.showToast({
				title: '发送失败',
				icon: 'error'
			})
		}
		beforeSendCode()
	}

	function clearSendCodeTimer() {
		if (timer > 0) clearInterval(timer)
		timer = 0
		currentTime.value = 0
	}
	async function beforeSendCode() {
		try {
			const params = {}
			const { code, data } = await requestApi.getMobileCodeEncryption(params)
			if(code === 10000) {
				console.log('加密前：',data);
				const result = encrypt(data)
				console.log('加密后：',result);
				const result1 = decrypt(result)
				console.log('解密后：',result1);
				sendCode(result)
			} else {
				uni.showToast({
					title: '发送失败1',
					icon: 'error'
				})
			}
		} catch (e) {
			console.error(e);
			uni.showToast({
				title: '发送失败2',
				icon: 'none'
			})
		}
	}
	async function sendCode(uuidCode) {
		try {
			const params = {
				params: {
					phone: loginForm1.mobile,
					uuidCode, // AES加密
				}
			}
			const { code } = await requestApi.sendMobileCode(params)
			if(code === 10000) {
				uni.showToast({
					title: '发送成功',
					icon: 'success'
				})
			} else {
				uni.showToast({
					title: '发送失败1',
					icon: 'error'
				})
			}
		} catch (e) {
			console.error(e);
			uni.showToast({
				title: '发送失败2',
				icon: 'none'
			})
		}
	}
	async function loginByCode() {
		if (!verifyMobile(loginForm1.mobile.trim())) {
			uni.showToast({
				title: '手机号错误',
				icon: 'none'
			})
			return
		}
		if (!verifyCode(loginForm1.code.trim())) {
			uni.showToast({
				title: '验证码错误',
				icon: 'none'
			})
			return
		}
		try {
			login_loading.value = true
			const params = {
				params: {
					phone: loginForm1.mobile,
					code: loginForm1.code
				}
			}
			const { code, data } = await requestApi.loginByYZW(params)
			if(code === 10000) {
				const result = data
				loginSuccess(data)
			} else {
				uni.showToast({
					title: '登录失败1',
					icon: 'error'
				})
			}
		} catch (e) {
			console.error(e);
			uni.showToast({
				title: '登录失败2',
				icon: 'none'
			})
		} finally {
			login_loading.value = false
		}
	}
	// 密码登录
	async function loginByPassword() {
		if (!verifyMobile(loginForm2.mobile.trim())) {
			uni.showToast({
				title: '手机号错误',
				icon: 'none'
			})
			return
		}
		if (!verifyPassword(loginForm2.password.trim())) {
			uni.showToast({
				title: '密码错误',
				icon: 'none'
			})
			return
		}
		try {
			login_loading.value = true
			const params = {
				params: {
					logname: loginForm2.mobile,
					pwd: loginForm2.password
				}
			}
			const { code, data } = await requestApi.loginByPwd(params)
			if(code === 10000) {
				const result = data
				loginSuccess(result)
			} else {
				uni.showToast({
					title: '登录失败1',
					icon: 'error'
				})
			}
		} catch (e) {
			console.error(e);
			uni.showToast({
				title: '登录失败2',
				icon: 'none'
			})
		} finally {
			login_loading.value = false
		}
	}

	onBeforeUnmount(() => {
		clearSendCodeTimer()
	})
</script>

<template>
	<view class="zg__page">
		<!-- 背景区 -->
		<view class="zg__bg">
			<!-- 导航栏 -->
			<view class="zg__navbar">
				<uni-icons class="zg__navbar--icon" type="left" size="30" color="#fff" @click="onBack"></uni-icons>
			</view>
			<!-- 介绍 -->
			<view class="zg__description">
				您好，<br />欢迎使用伊鸣智联
			</view>
		</view>
		<!-- 登录区 -->
		<view class="zg__login">
			<!-- 标签栏 -->
			<view class="zg__tabbar">
				<view class="zg__tabbarItem" :class="{ zg__tabbarItem__active: tabbarIndex === i }"
					v-for="(v,i) in tabbarList" :key="i" @click="onChangeTabbar(v,i)">
					{{ v.name }}
				</view>
			</view>
			<!-- 验证码登录 -->
			<view class="zg__form" v-show="tabbarIndex === 0">
				<!-- 手机号 -->
				<view class="zg__formItem">
					<image class="zg__formItem--image" src="../../static/icons/shouji@3x.png" mode="widthFix"></image>
					<input class="zg__formItem--input" type="number" placeholder="请输入手机号"
						placeholder-class="zg__input__placeholder" v-model="loginForm1.mobile" />
				</view>
				<!-- 验证码 -->
				<view class="zg__formItem">
					<image class="zg__formItem--image" src="../../static/icons/yanzheng@3x.png" mode="widthFix"></image>
					<input class="zg__formItem--input" type="number" placeholder="请输入验证码"
						placeholder-class="zg__input__placeholder" v-model="loginForm1.code" />
					<view class="zg__formItem--button" :class="{'zg__formItem--button__disabled': currentTime > 0}"
						@click="onSendCode">{{ codeText }}</view>
				</view>
			</view>
			<!-- 密码登录 -->
			<view class="zg__form" v-show="tabbarIndex === 1">
				<!-- 手机号 -->
				<view class="zg__formItem">
					<image class="zg__formItem--image" src="../../static/icons/shouji@3x.png" mode="widthFix"></image>
					<input class="zg__formItem--input" type="number" placeholder="请输入手机号"
						placeholder-class="zg__input__placeholder" v-model="loginForm2.mobile" />
				</view>
				<!-- 密码 -->
				<view class="zg__formItem">
					<image class="zg__formItem--image" src="../../static/icons/mima@3x.png" mode="widthFix"></image>
					<input class="zg__formItem--input" type="password" placeholder="请输入密码"
						placeholder-class="zg__input__placeholder" v-model="loginForm2.password" />
				</view>
			</view>
			<!-- 登录按钮 -->
			<view class="zg__formSubmit">
				<button class="zg__formSubmit--button" type="primary" :loading="login_loading"
					@click="login">登录</button>
			</view>
			<!-- 用户协议 -->
			<view class="zg__formAgreement">
				<uni-icons class="zg__formAgreement--icon" type="checkbox-filled" size="22" color="#007aff"
					v-show="isAgree" @click="isAgree=false"></uni-icons>
				<uni-icons class="zg__formAgreement--icon" type="circle" size="22" color="#999" v-show="!isAgree"
					@click="isAgree=true"></uni-icons>
				<text class="zg__formAgreement--text">我已阅读并同意</text>
				<navigator class="zg__formAgreement--navigator" url="/pages/user/agreement">《用户协议》</navigator>
			</view>
		</view>
	</view>
</template>

<style lang="scss" scoped>
	page {
		background-color: #aaa;
	}

	.zg__page {
		height: 100vh;
		color: $uni-text-color;
	}

	.zg__bg {
		background-image: url('../../static/icons/bg@3x.png');
		background-repeat: no-repeat;
		background-size: cover;
		color: $uni-text-color-inverse;
		box-sizing: border-box;
		height: calc(600 / 1125 * 750rpx);
		padding: 30rpx 10rpx;
	}

	.zg__navbar {
		&--icon {
			cursor: pointer;
		}
	}

	.zg__description {
		margin-top: 8%;
		font-size: 42rpx;
		line-height: 1.6;
		padding: 0 60rpx;
	}

	.zg__login {
		box-sizing: border-box;
		height: calc(100vh - 600 / 1125 * 750rpx + 30rpx);
		background-color: $uni-bg-color;
		padding: 10rpx 80rpx;
		margin-top: -30rpx;
		border-radius: 40rpx 40rpx 0 0;
	}

	.zg__tabbar {
		display: flex;
		align-items: center;
		justify-content: space-between;

		&Item {
			font-size: 36rpx;
			padding: 15rpx 20rpx;
			color: $uni-text-color-grey;
			cursor: pointer;

			&__active {
				color: $uni-color-primary;
				font-weight: bold;
				position: relative;

				&::after {
					content: "";
					display: block;
					width: 50rpx;
					height: 8rpx;
					border-radius: 4rpx;
					background-color: $uni-color-primary;
					position: absolute;
					bottom: 0rpx;
					left: 50%;
					margin-left: -25rpx;
				}
			}
		}
	}


	.zg__form {
		margin-top: 60rpx;
		display: flex;
		flex-direction: column;
		gap: 20rpx;

		&Item {
			width: 100%;
			display: flex;
			align-items: center;
			gap: 30rpx;
			background-color: $uni-bg-color-input;
			height: 100rpx;
			border-radius: 50rpx;
			padding: 0 30rpx;
			box-sizing: border-box;

			&--image {
				width: 42rpx;
				height: auto;
				flex-shrink: 0;
			}

			&--input {
				flex-grow: 1;
				height: 100%;
				font-size: 30rpx;
			}

			&--button {
				flex-shrink: 0;
				font-size: 30rpx;
				color: $uni-color-primary;
				cursor: pointer;

				&__disabled {
					cursor: not-allowed;
					color: $uni-text-color-grey;
				}
			}
		}
	}

	.zg__formSubmit {
		margin-top: 30rpx;

		&--button {
			padding: 0;
			height: 100rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			border-radius: 50rpx;
			background: linear-gradient(to right, rgb(84, 147, 245), $uni-color-primary);
		}
	}

	.zg__formAgreement {
		display: flex;
		align-items: center;
		justify-content: center;
		gap: 10rpx;
		font-size: 28rpx;
		margin-top: 30rpx;

		&--icon {}

		&--text {
			color: $uni-color-subtitle;
		}

		&--navigator {
			color: $uni-color-primary;
		}
	}
</style>